local desc_hxstar_shop = [[
  # 将星招募模式简介

  ___

  ## 该模式为2斗地主模式的衍生模式，玩家可消耗金豆进行一些操作。
  
  ## v0.1
  1.框架基本完成，可以在该模式内游玩2斗地主、体验抽武将。
  ## v0.2
  1.实装兑换diy武将的功能。

]]

local HX = require "packages/huixiangkill/hxfs"

local hxstar_shop_getLogic = function()
  local hxstar_shop_logic = GameLogic:subclass("hxstar_shop_logic")

  function hxstar_shop_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = { nil, nil, { "lord", "rebel", "rebel" }, }
  end

  function hxstar_shop_logic:assignRoles()
    local room = self.room
    local n = #room.players

    local roles = self.role_table[n]
    table.shuffle(roles)

    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end
  end

  function hxstar_shop_logic:adjustSeats()
    local player_circle = {}
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end

  function hxstar_shop_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    local players = room.players
    local noai = table.filter(players, function(p) return p.id > 0 end)
    local maylord = players[math.random(1,#players)]
    local lord = maylord
    maylord.role = "lord"
    room:setCurrent(maylord)

    local list = {
      "hxstar_shop-testbuy",
      "hxstar_shop-buy10",
      "hxstar_shop-1v2",
      "hxstar_shop-over",
    }
    local to1v2 = 0
    local toover = 0
    while to1v2 < #noai and toover == 0 do
      for _, p in ipairs(noai) do
        local pname = p._splayer:getScreenName()
        local num = HX.GetPlayerMoney(room, "hx_1v2_jindou", p)
        local choices = table.simpleClone(list)
        if num < 100000 then
          table.removeOne(choices, "hxstar_shop-buy10")
        end
        local choice = room:askToChoice(p, {
          choices = choices,
          all_choices = list,
          skill_name = "将星招募：你当前有" .. num .. "金豆，想做点什么？",
          prompt = "将星招募：你当前有" .. num .. "金豆，想做点什么？",
          detailed = true,
          cancelable = false,
        })
        if choice == "hxstar_shop-1v2" then
          room:sendLog{ type = "%arg 选择了来一把2斗地主", toast = true, arg = pname }
          to1v2 = to1v2 + 1
        elseif choice == "hxstar_shop-over" then
          room:sendLog{ type = "%arg 选择了离开将星招募", toast = true, arg = pname }
          toover = toover + 1
        elseif choice == "hxstar_shop-testbuy" then
          room:sendLog{ type = "%arg 选择了抽一次武将", toast = true, arg = pname }
          local all_generals = {}
          for general_name, _ in pairs(Fk.generals) do
            table.insert(all_generals, general_name)
          end
          local buy = all_generals[math.random(1,#all_generals)]
          room:prepareGeneral(p, buy, nil, true)
          room:sendLog{ type = "%arg 抽到了 %arg2 ！", toast = true, arg = pname, arg2 = Fk:translate(buy), }
        elseif choice == "hxstar_shop-buy10" then
          room:sendLog{ type = "%arg 选择了消耗10万金豆！请截图保存二维码填写信息！", toast = true, arg = pname }
          HX.ChangePlayerMoney(room, "hx_1v2_jindou", p, -100000)
          room:doAnimate("SuperLightBox", {
            path = "packages/huixiangkill/qml/buy10.qml",
          },{p})
          print("恭喜",pname,"消耗10万金豆，获得了diy武将！")
          room:doBroadcastNotify("ServerMessage", string.format(
          "恭喜玩家 <font color=\"#FFA07A\"><b>"..pname.."</b></font> 在 <font color=\"#87CEFA\"><b>将星招募模式</b></font> 中获得了 <font color=\"#E0DB2F\"><b>diy武将</b></font> ，大家快恭喜TA吧"
          ))
          room:doBroadcastNotify("ServerMessage", string.format(
          "恭喜玩家 <font color=\"#FFA07A\"><b>"..pname.."</b></font> 在 <font color=\"#87CEFA\"><b>将星招募模式</b></font> 中获得了 <font color=\"#E0DB2F\"><b>diy武将</b></font> ，大家快恭喜TA吧"
          ))
        end
      end
    end
    if toover > 0 then
      room:gameOver("")
    end
    if to1v2 < #noai then
      room:gameOver("")
    end
    local a1 = #room.general_pile
    local a2 = #room.players * generalNum
    if a1 < a2 then
      room:sendLog{
        type = "#NoEnoughGeneralDraw",
        arg = a1,
        arg2 = a2,
        toast = true,
      }
      room:gameOver("")
    end
    local generals = room:getNGenerals(#players * generalNum)
    local data_table = {}
    local noai_data_table = {}
    local sortplayers = {}  --对玩家排序,不然迷你游戏会有问题,各个玩家的武将也可能会重复
    for _, p in ipairs(noai) do
      table.insert(sortplayers, p)
    end
    for _, p in ipairs(players) do
      if not table.contains(noai, p) then
        table.insert(sortplayers, p)
      end
    end
    for i, p in ipairs(sortplayers) do  --用排序后的玩家列表
      local start_index = (i - 1) * generalNum + 1
      local end_index = i * generalNum + 1
      local pname = p._splayer:getScreenName()
      data_table[p.id] = {
        generals = table.slice(generals, start_index, end_index),
        enable = i, ---- 玩家次序
        index = 1,  ---- 当前次序
        pname = pname, ----玩家名称
        cancel = 0,
        num = 0,
      }
      if table.contains(noai, p) then
        noai_data_table[p.id] = data_table[p.id]
      end
    end
    room:doBroadcastNotify("ShowToast", "当前正在选择倍率的玩家是"..noai_data_table[sortplayers[1].id].pname.."")
    while true do
      local cancel = room:getBanner("hx__1v2__cancel") or 0
      for _, p in ipairs(noai) do
        local num = HX.GetPlayerMoney(room, "hx_1v2_jindou", p)
        local lost = room:getBanner("hx_1v2_lost"..p.id) or 0
        num = num - lost
        noai_data_table[p.id].num = num
        noai_data_table[p.id].cancel = cancel
        room:setPlayerMark(p, "@!!hx_1v2_jindou", num)
        room:setPlayerMark(p, "@[hxjindou]hx_1v2_jindou", 1)
      end
      if cancel >= 2 then
        break
      end
      room:askToMiniGame(noai, {
        skill_name = "hx__1v2_selectdizhu",
        game_type = "hx__1v2_selectdizhu",
        data_table = noai_data_table,
      })
      --得分最高者为地主,否则为原来的随机地主
      local maxpoint = 100
      local nowcancel = 0
      for i, p in ipairs(noai) do
        local point = p.reply_ready and tonumber(p.client_reply) or tonumber(p.default_reply)
        point = point or 1
        if point == 1 then
          nowcancel = nowcancel + 1
        else
          point = point * 100
          local before = room:getBanner("hx_1v2_lost"..p.id) or 0
          point = point + before
          room:setBanner("hx_1v2_lost"..p.id, point)
          if point > maxpoint then
            maxpoint = point
            lord = p
            room:setBanner("@hx__1v2_mode_POINT", point)
          end
          local num = HX.GetPlayerMoney(room, "hx_1v2_jindou", p)
          num = num - point
          room:setPlayerMark(p, "@!!hx_1v2_jindou", num)
          room:setPlayerMark(p, "@[hxjindou]hx_1v2_jindou", 1)
        end
        if #noai == 1 and point <= 100 then  ----仅一名玩家且叫分不超过100则为随机地主
          lord = maylord
        end
      end
      room:setBanner("hx__1v2__cancel", nowcancel)
      if #noai == 1 then
        break
      end
    end


    --无人抢地主时设置倍率
    if room:getBanner("@hx__1v2_mode_POINT") == nil then
      room:setBanner("@hx__1v2_mode_POINT", 100)
    end

    ----分配身份和座位
    for i, p in ipairs(players) do
      if p.id == lord.id then
        p.role = "lord"
      else
        p.role = "rebel"
      end
    end

    for _, p in ipairs(players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    local nonlord = room:getOtherPlayers(lord)
    nonlord[1]:addBuddy(nonlord[2])
    nonlord[2]:addBuddy(nonlord[1])

    local player_circle = {}
    local x = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        x = i
        break
      end
    end
    for j = x, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, x - 1 do
      table.insert(player_circle, players[j])
    end

    room:arrangeSeats(player_circle)

    local seats = {}
    for _, p in ipairs(noai) do
      table.insert(seats, p.seat)
    end
    table.sort(seats, function(a, b) return a > b end)

    --获取可换的武将，人机就不换将了，座位靠后的先得换将卡
    local function getChange(all_cards, can_change, id)
      if not table.contains(noai, room:getPlayerById(id)) then
        return {}
      end
      local seat = room:getPlayerById(id).seat
      local change = {}
      local index = 0
      for i, s in ipairs(seats) do
        if s == seat then
          index = i
          break
        end
      end
      local start_index = (index - 1) * can_change + 1
      local end_index = index * can_change + 1
      change = table.slice(all_cards, start_index, end_index)
      return change
    end

    local can_change = room:getBanner("changeGeneralNum") or generalNum --换将次数
    local all_cards = table.map(HX.getGenerals((can_change * #noai) + 2, room.general_pile, generals), Util.NameMapper)
    table.shuffle(all_cards)

    local data_table_true = {}
    for _, p in ipairs(players) do
      local arg = data_table[p.id].generals
      if p.role == "lord" then  ----地主多发两个武将
        local count = #all_cards
        arg[#arg+ 1] = all_cards[count]
        arg[#arg + 1] = all_cards[count - 1]
      end
      data_table_true[p.id] = {
        change = getChange(all_cards, can_change, p.id),
        cards = arg,  --generals
        num = n,  --n
        no_c = false, --no_convert
        heg = false, --heg
        type = "askForGeneralsChosen", --rule
        extra = {n = n}, --extra_data
      }
    end
    room:askToMiniGame(players, {
      skill_name = "AskForGeneral",
      game_type = "ChooseGeneralWithCanChange",
      data_table = data_table_true,
      timeout = self.room.settings.generalTimeout,
    })

    for _, p in ipairs(players) do
      local result = p.client_reply
      local general = result[1]
      local deputy = result[2]
      room:prepareGeneral(p, general, deputy)
    end
    room:askToChooseKingdom(players)
    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "deputyGeneral")
    end

  end

  function hxstar_shop_logic:attachSkillToPlayers()
    local room = self.room
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: " .. skillName .. " doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then
        return
      end
      if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
        return
      end
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        for _, s in ipairs(deputy:getSkillNameList(false)) do
          addRoleModSkills(p, s)
        end
      end
      if p.role == "lord" then
        room:handleAddLoseSkills(p, "m_feiyang|m_bahu", nil, false)
        local mobilegeneral = {}
        for _, general in ipairs(Fk:getAllGenerals()) do
          if general.package.extensionName == "mobile" or general.package.extensionName == "mougong" then
            table.insertIfNeed(mobilegeneral, general)
          end
        end
        if #mobilegeneral / #Fk:getAllGenerals() >= 0.5 then
          room:sendLog{ type = "#hx_1v2_skill_tips", toast = true }
          room:delay(2000)
          room:handleAddLoseSkills(p, "hx_1v2__qiangyi", nil, false)
        end
      end
    end
  end

  return hxstar_shop_logic
end

local hxstar_shop = fk.CreateGameMode {
  name = "hxstar_shop",
  minPlayer = 3,
  maxPlayer = 3,
  logic = hxstar_shop_getLogic,
  main_mode = "1v2_mode",
  rule = "#hxstar_shop_rule&",
  is_counted = function(self, room)
    return #room.players >= 2
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 30 s", passed = playedTime >= 30 } }
    if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "1v2: left you alive", passed = #Fk:currentRoom().alive_players == 2 })
    end
    return surrenderJudge
  end,
  get_adjusted = function(self, player)
    if player.role == "lord" then
      return { hp = player.hp + 1, maxHp = player.maxHp + 1 }
    end
    return {}
  end,
  reward_punish = function(self, victim, killer)
    local room = victim.room
    if victim.role == "rebel" then
      for _, p in ipairs(room:getOtherPlayers(victim)) do
        if p.role == "rebel" then
          local choices = { "draw2", "Cancel" }
          if p:isWounded() then
            table.insert(choices, 2, "recover")
          end
          local choice = room:askToChoice(p, {
            choices = choices,
            skill_name = "PickLegacy",
          })
          if choice == "draw2" then
            p:drawCards(2, "game_rule")
          else
            room:recover {
              who = p,
              num = 1,
              recoverBy = p,
              skillName = "game_rule",
            }
          end
        end
      end
    end
  end,
}

Fk:loadTranslationTable{
  ["hxstar_shop"] = "将星招募v0.2",
  [":hxstar_shop"] = desc_hxstar_shop,

  ["hxstar_shop-1v2"] = "来一把2斗地主",
  [":hxstar_shop-1v2"] = "所有玩家都选择了此选项则会进行一局2斗地主",
  ["hxstar_shop-testbuy"] = "抽一次武将",
  [":hxstar_shop-testbuy"] = "当前为测试阶段，该选择会抽一张武将作为你的主将，仅供娱乐",
  ["hxstar_shop-over"] = "离开将星招募",
  [":hxstar_shop-over"] = "有玩家选择了此选项则会再本轮询问结束后结束游戏",
  ["hxstar_shop-buy10"] = "消耗10万金豆",
  [":hxstar_shop-buy10"] = "消耗10万金豆，获得diy武将！diy武将会被放在回想包的 <b>回想·将星</b> 中",


}

return hxstar_shop
